package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import dao.MerchantDao;
import pojo.Merchant;

@Repository
public class MerchantDaoImpl implements MerchantDao {
	@PersistenceContext(name="un")
	private EntityManager manager; 
	
	@Override
	public Merchant findByName(Merchant merchant) {
		String ql="select m from Merchant m where m.name=?";
		System.out.println("dao pass"+merchant.getPassword());
		List<Merchant> merchant_result = (List<Merchant>) manager.createQuery(ql).setParameter(1, merchant.getName()).getResultList();
		
		if(merchant_result.size() == 0 || merchant_result == null){
			return null;
		}
		return merchant_result.get(0);
	}
	
	@Override
	public Merchant add(Merchant merchant) {
		manager.persist(merchant);
		return merchant;
	}

	@Override
	public Merchant update(Merchant merchant) {
		Merchant dbMerchant = manager.find(Merchant.class, merchant.getId());
		dbMerchant.setPassword(merchant.getPassword());
		dbMerchant.setAvatarPath(merchant.getAvatarPath());
		dbMerchant.setIdCardPath(merchant.getIdCardPath());
		dbMerchant.setAddress(merchant.getAddress());
		Merchant mm = manager.merge(dbMerchant);
		return mm;
	}

}
